package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Configuration
@RestControllerAdvice   //SpringMVC异常拦截器
@Slf4j
public class ExceptionCatch {

    //未知异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception ex){
        //记录日志
        log.error("ExceptionCatch ex:{}",ex);
        //发邮件通知服务器内部错误
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    //已知异常
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public ResponseResult custException(CustomException ex){
        log.error("ExceptionCatch ex:{}",ex);
        //得到异常信息
        AppHttpCodeEnum appHttpCodeEnum = ex.getAppHttpCodeEnum();
        return ResponseResult.errorResult(appHttpCodeEnum);
    }
}